package com.ruoyi.common.baidu;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.Base64;
import com.alibaba.fastjson2.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import com.ruoyi.common.enums.BaiduOcrParamEnum;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 百度云OCR调用工具
 *
 * @author liaowen
 * @date 2024/11/7 17:30
 */
@Slf4j
@Component
public class BaiduOcrUtil {
    /**
     * 获取access_token
     */
    private static final String ACCESS_TOKEN_HOST = "https://aip.baidubce.com/oauth/2.0/token?";
    /**
     * 身份证识别
     */
    private static final String SFZ_OCR_HOST = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?";
    /**
     * 营业执照识别
     */
    private static final String YYZZ_OCR_HOST = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?";

    /**
     * appId
     */
    private static final String APP_ID = "116155269";
    /**
     * api_key
     */
    private static final String API_KEY = "y6cdKUpif3hFc0QUfUHST0ag";
    /**
     * api_secret
     */
    private static final String SECRET_KEY = "zIPf6YYAVVwrYeqCG8xlqF9D5c7S9Sz0";


    @Autowired
    private BaiduRequestClient baiduRequestClient;


    /**
     * 获取百度云OCR的授权access_token
     *
     * @return
     */
    private String getAccessTokenByForest() {
        try {
            JSONObject jsonObject = baiduRequestClient.getAccessToken(API_KEY, SECRET_KEY);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            log.error("获取百度token失败：", e);
            return null;
        }
    }


    /**
     * 获取百度云OCR的授权access_token
     *
     * @return
     */
    private String getAccessToken() {
        return getAccessToken(API_KEY, SECRET_KEY);
    }

    /**
     * 获取百度云OCR的授权access_token
     *
     * @param apiKey
     * @param secretKey
     * @return
     */
    private String getAccessToken(String apiKey, String secretKey) {
        String accessTokenURL = ACCESS_TOKEN_HOST
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + apiKey
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + secretKey;

        try {
            URL url = new URL(accessTokenURL);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            // 获取响应头
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info(key + "---->" + map.get(key));
            }

            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                result.append(inputLine);
            }
            JSONObject jsonObject = JSONObject.parseObject(result.toString());
            return jsonObject.getString("access_token");

        } catch (Exception e) {
            log.error("获取access_token失败: ", e);
            return null;
        }
    }


    /**
     * 获取身份证识别后的数据
     *
     * @param imageUrl
     * @return
     */
    public Map<String, String> getRecognitionResult(File imageUrl, BaiduOcrParamEnum ocrParamEnum) {
        if (ObjectUtil.isNull(ocrParamEnum) || ObjectUtil.isNull(imageUrl)) {
            log.error("参数为空：");
            return null;
        }
        if (BaiduOcrParamEnum.FRONT.equals(ocrParamEnum) || BaiduOcrParamEnum.BACK.equals(ocrParamEnum)) {
            String value = getStringIdentityCard(imageUrl, ocrParamEnum);
            if (StringUtils.isBlank(value)) {
                return null;
            }
            Map<String, String> map = new HashMap<>();
            JSONObject jsonObject = JSONObject.parseObject(value);
            JSONObject wordsResult = jsonObject.getJSONObject("words_result");
            if (wordsResult == null || wordsResult.isEmpty()) {
                log.error("识别结果为空：value = {}", value);
                return null;
            }
            for (String key : wordsResult.keySet()) {
                JSONObject result = wordsResult.getJSONObject(key);
                String info = result.getString("words");
                switch (key) {
                    case "姓名":
                        map.put("realName", info);
                        break;
                    case "性别":
                        map.put("sex", info);
                        break;
                    case "民族":
                        map.put("nationality", info);
                        break;
                    case "出生":
                        map.put("birthday", info);
                        break;
                    case "住址":
                        map.put("address", info);
                        break;
                    case "公民身份号码":
                        map.put("number", info);
                        break;
                    case "签发机关":
                        map.put("issuedOrganization", info);
                        break;
                    case "签发日期":
                        map.put("issuedAt", info);
                        break;
                    case "失效日期":
                        map.put("expiredAt", info);
                        break;
                }
            }
            if (map.containsKey("issuedAt") && map.containsKey("expiredAt")) {
                // 有效期
                map.put("validityPeriod", map.get("issuedAt") + " - " + map.get("expiredAt"));
            }
            return map;
        }
        if (BaiduOcrParamEnum.BUSINESS.equals(ocrParamEnum)) {
            String value = getStringBusiness(imageUrl);
            if (StringUtils.isBlank(value)) {
                return null;
            }
            Map<String, String> map = new HashMap<>();
            JSONObject jsonObject = JSONObject.parseObject(value);
            JSONObject wordsResult = jsonObject.getJSONObject("words_result");
            if (wordsResult == null || wordsResult.isEmpty()) {
                log.error("识别结果为空：value = {}", value);
                return null;
            }
            for (String key : wordsResult.keySet()) {
                JSONObject result = wordsResult.getJSONObject(key);
                String info = result.getString("words");
                switch (key) {
                    case "社会信用代码":
                        map.put("socialCreditCode", info);
                        break;
                    case "单位名称":
                        map.put("companyName", info);
                        break;
                    case "类型":
                        map.put("companyType", info);
                        break;
                    case "法人":
                        map.put("legalPerson", info);
                        break;
                    case "注册资本":
                        map.put("registeredCapital", info);
                        break;
                    case "成立日期":
                        map.put("establishDate", info);
                        break;
                    case "地址":
                        map.put("registeredAddress", info);
                        break;
                    case "经营范围":
                        map.put("businessScope", info);
                        break;
                    case "有效期":
                        map.put("validTerm", info);
                        break;
                    case "有效期起始日期":
                        map.put("validTermBegin", info);
                        break;
                }
            }
            return map;
        }
        return null;
    }

    /**
     * 获取身份证识别后的数据
     *
     * @param imageUrl
     * @return
     */
    private String getStringIdentityCard(File imageUrl, BaiduOcrParamEnum ocrParamEnum) {
        if (ObjectUtil.isNull(ocrParamEnum)) {
            return null;
        }
        // 身份证OCR的http URL+鉴权token
        String OCRUrl = SFZ_OCR_HOST + "access_token=" + getAccessToken();
        // 对图片进行base64处理
        String image = encodeImageToBase64(imageUrl);
        // 请求参数
        String value = ocrParamEnum.getValue();
        String requestParam = "detect_direction=true&id_card_side=" + value + "&image=" + image;

        try {
            // 请求OCR地址
            URL url = new URL(OCRUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("apiKey", API_KEY);
            connection.setDoOutput(true);
            connection.getOutputStream().write(requestParam.getBytes(StandardCharsets.UTF_8));
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                result.append(inputLine);
            }
            bufferedReader.close();
            return result.toString();
        } catch (Exception e) {
            log.error("身份证OCR识别异常: ", e);
            return null;
        }
    }

    /**
     * 获取营业执照识别后的数据
     *
     * @param imageUrl
     * @return
     */
    private String getStringBusiness(File imageUrl) {
        // 营业执照OCR的http URL+鉴权token
        String OCRUrl = YYZZ_OCR_HOST + "access_token=" + getAccessToken();
        // 对图片进行base64处理
        String image = encodeImageToBase64(imageUrl);
        // 请求参数
        String requestParam = "detect_direction=true&image=" + image;

        try {
            // 请求OCR地址
            URL url = new URL(OCRUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("apiKey", API_KEY);
            connection.setDoOutput(true);
            connection.getOutputStream().write(requestParam.getBytes(StandardCharsets.UTF_8));
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                result.append(inputLine);
            }
            bufferedReader.close();
            return result.toString();
        } catch (Exception e) {
            log.error("营业执照OCR识别异常: ", e);
            return null;
        }
    }

    /**
     * 对图片url进行Base64编码处理
     *
     * @param imageUrl
     * @return
     */
    private String encodeImageToBase64(File imageUrl) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        try {
            InputStream inputStream = new FileInputStream(imageUrl);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();

            // 对字节数组Base64编码
            return URLEncoder.encode(Base64.byteArrayToBase64(data), "UTF-8");
        } catch (Exception e) {
            log.error("对图片url进行Base64编码处理异常: ", e);
            return null;
        }

    }


    /**
     * MultipartFile 转 File
     *
     * @throws Exception
     */
    public File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    /**
     * 文件读取为字节数组
     *
     * @param file
     * @return
     * @throws IOException
     */
    public byte[] readFileByBytes(File file) throws IOException {
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream(((int) file.length()));
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            int bufSize = 1024;
            byte[] buffer = new byte[bufSize];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, bufSize))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭文件流处理异常: ", e);
            }
            bos.close();
        }
    }

    //获取流文件
    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            throw new ServiceException();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

    /**
     * 使用百度sdk方式，识别图片文字
     *
     * @param file
     * @param ocrParamEnum
     * @return
     * @throws Exception
     */
    public Map<String, String> getRecognitionResultBaidu(File file, BaiduOcrParamEnum ocrParamEnum) throws Exception {
        if (ObjectUtil.isNull(ocrParamEnum) || ObjectUtil.isNull(file)) {
            log.error("参数为空：");
            return null;
        }
        if (BaiduOcrParamEnum.FRONT.equals(ocrParamEnum) || BaiduOcrParamEnum.BACK.equals(ocrParamEnum)) {
            return getStringIdentityCardMap(file, ocrParamEnum);
        }
        if (BaiduOcrParamEnum.BUSINESS.equals(ocrParamEnum)) {
            return getStringBusinessMap(file);
        }
        return null;
    }

    /**
     * 失败身份证
     *
     * @param file
     * @param ocrParamEnum
     * @return
     * @throws Exception
     */
    private Map<String, String> getStringIdentityCardMap(File file, BaiduOcrParamEnum ocrParamEnum) throws Exception {
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        HashMap<String, String> options = new HashMap<>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");
        byte[] bytes = readFileByBytes(file);
        org.json.JSONObject jsonObject = client.idcard(bytes, ocrParamEnum.getValue(), options);
        org.json.JSONObject wordsResult = jsonObject.getJSONObject("words_result");
        if (wordsResult == null || wordsResult.length() == 0) {
            log.error("识别结果为空：value = {}", jsonObject);
            return null;
        }

        Map<String, String> map = new HashMap<>();
        Iterator keys = wordsResult.keys();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            org.json.JSONObject result = wordsResult.getJSONObject(key);
            String info = result.getString("words");
            switch (key) {
                case "姓名":
                    map.put("realName", info);
                    break;
                case "性别":
                    map.put("sex", info);
                    break;
                case "民族":
                    map.put("nationality", info);
                    break;
                case "出生":
                    map.put("birthday", info);
                    break;
                case "住址":
                    map.put("address", info);
                    break;
                case "公民身份号码":
                    map.put("number", info);
                    break;
                case "签发机关":
                    map.put("issuedOrganization", info);
                    break;
                case "签发日期":
                    map.put("issuedAt", info);
                    break;
                case "失效日期":
                    map.put("expiredAt", info);
                    break;
            }
        }
        if (map.containsKey("issuedAt") && map.containsKey("expiredAt")) {
            // 有效期
            map.put("validityPeriod", map.get("issuedAt") + " - " + map.get("expiredAt"));
        }
        return map;
    }

    /**
     * 识别营业执照
     *
     * @param file
     * @return
     * @throws Exception
     */
    private Map<String, String> getStringBusinessMap(File file) throws Exception {
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        HashMap<String, String> options = new HashMap<>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");
        byte[] bytes = readFileByBytes(file);
        org.json.JSONObject jsonObject = client.businessLicense(bytes, options);
        org.json.JSONObject wordsResult = jsonObject.getJSONObject("words_result");
        if (wordsResult == null || wordsResult.length() == 0) {
            log.error("识别结果为空：value = {}", jsonObject);
            return null;
        }

        Map<String, String> map = new HashMap<>();
        Iterator keys = wordsResult.keys();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            org.json.JSONObject result = wordsResult.getJSONObject(key);
            String info = result.getString("words");
            switch (key) {
                case "社会信用代码":
                    map.put("socialCreditCode", info);
                    break;
                case "单位名称":
                    map.put("companyName", info);
                    break;
                case "类型":
                    map.put("companyType", info);
                    break;
                case "法人":
                    map.put("legalPerson", info);
                    break;
                case "注册资本":
                    map.put("registeredCapital", info);
                    break;
                case "成立日期":
                    map.put("establishDate", info);
                    break;
                case "地址":
                    map.put("registeredAddress", info);
                    break;
                case "经营范围":
                    map.put("businessScope", info);
                    break;
                case "有效期":
                    map.put("validTerm", info);
                    break;
                case "有效期起始日期":
                    map.put("validTermBegin", info);
                    break;
            }
        }
        return map;
    }

}
